/*
 *  Copyright (c) 2013.
 *  * 游戏服务器核心代码编写人陈磊拥有使用权
 *  * 联系方式：E-mail:13638363871@163.com ;qq:502959937
 *  * 个人博客主页：http://my.oschina.net/chenleijava
 */

package com.dc.gameserver.serverCore.model.dbsql.modelService;

import com.dc.gameserver.baseConfig.Config;
import com.dc.gameserver.exceptions.dataException;
import com.dc.gameserver.proto.itemserverprotoVo.*;
import com.dc.gameserver.serverCore.model.dbsql.mapper.*;
import com.dc.gameserver.serverCore.model.dbsql.modelCache.ModelCacheService;
import com.dc.gameserver.serverCore.model.dbsql.modelVo.*;
import com.dc.gameserver.serverCore.model.gamemodel.BookModel;
import com.dc.gameserver.serverCore.model.gamemodel.EquipmentModel;
import com.dc.gameserver.serverCore.model.gamemodel.PropsModel;
import com.dc.gameserver.serverCore.model.gamemodel.script.ScriptFactory;
import com.dc.gameserver.serverCore.service.cardModule.CardBox;
import com.dc.gameserver.serverCore.service.character.GameCharacter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 石头哥哥 on 13-12-17.
 */
@Service
@SuppressWarnings("unchecked")
public class RoleItemService {

    //玩家道具信息列表
    @Resource
    private TRoleItemPropsMapper tRoleItemPropsMapper;

    //玩家装备列表
    @Resource
    private TRoleEquMapper tRoleEquMapper;

    //秘籍信息列表
    @Resource
    private TRoleBookMapper tRoleBookMapper;


    @Resource
    private TSpriteMapper tSpriteMapper;


    @Resource
    private ModelCacheService modelCacheService;

    @Resource
    private TItemLogMapper itemLogMapper;


    /********物品系统******************************************/
    /**
     * 玩机获取战斗物品，系统主动掉落物品登记到玩家数据表
     * 物品记录 关联 角色背包系统
     * @param items   掉落物品信息  int[0]:关卡编号；int[1]：掉落的物品类型编号;int[2]:掉落物品数量；
     *                int[3]：物品类型--->1 装备 2.秘籍 3.道具；
     * @param optType 玩家操作数据库物品来源类型
     * @return  物品自增ID
     * info[0]:类型编号--->1:秘籍；2：装备；3.道具；info[1]:物品类型编号;info[2]:物品唯一ID；
     */
    @Transactional
    public void recordGoods(GameCharacter gameCharacter,int[] items,String optType){
        int roleID=gameCharacter.getID();
        try{
            boolean useItemLog=Config.DEFAULT_VALUE.GAME_VALUE.useItemLog;
            int num=items[0x2];
            //first record in itemLog
            //装备
            if (items[0x3]== 0x1){
                EquipmentModel equipmentModel=ScriptFactory.equipmentModelFastMap.get(items[0x1]);
                if (equipmentModel!=null){
                    if (useItemLog){
                        TItemLog itemLog=new  TItemLog();
                        itemLog.setRoleid(roleID);
                        itemLog.setCreattime(new Date());
                        itemLog.setOpttype(optType);
                        itemLog.setItemtypeid(equipmentModel.getId());
                        itemLog.setItemname(equipmentModel.getName());
                        itemLog.setInfo(equipmentModel.getIntro());
                        //log item
                        this.itemLogMapper.insert(itemLog); //物品日志记录
                    }
                    //记录到玩家的物品数据表中
                    TRoleEqu roleEqu=new TRoleEqu();
                    roleEqu.setOwnerid(roleID);  //装备所属对象
                    roleEqu.setEqutypeid(equipmentModel.getId());   //物品编号
                    roleEqu.setEqutype(equipmentModel.getType().byteValue());   //部位、类型
                    roleEqu.setEqupinzhi(equipmentModel.getQuality().byteValue());   //品质
                    roleEqu.setEqupinjie(equipmentModel.getSubQuality().byteValue());  //品阶
                    roleEqu.setEqulevel(equipmentModel.getUpgradeLevelMax());//强化等级
                    roleEqu.setEquprice(equipmentModel.getPrice());  //装备售价
                    roleEqu.setEqutimeout((long) 0);    //time out
                    roleEqu.setEqushowbag(equipmentModel.getShowInBag());  //show bag
                    roleEqu.setEqulocation((byte) -1);     //装备位置
                    roleEqu.setEqupinjieexp(0);
                    roleEqu.setItemtype(equipmentModel.getItemType());  //装备类型 1
                    roleEqu.setEffectnum1(equipmentModel.getEffectNum1());
                    roleEqu.setEffectnumgrowup1(equipmentModel.getEffectNumGrowUp1());
                    roleEqu.setEffectnum2(equipmentModel.getEffectNum2());
                    roleEqu.setEffectnumgrowup2(equipmentModel.getEffectNumGrowUp2());
                    roleEqu.setEffectnum3(equipmentModel.getEffectNum3());
                    roleEqu.setEffectnumgrowup3(equipmentModel.getEffectNumGrowUp3());

                    //更新DB  缓存
                    tRoleEquMapper.insert(roleEqu);  //
                    List<TRoleEqu> tRoleEquList=
                            (List<TRoleEqu>) modelCacheService.findListByPrefixID(ModelCacheService.EQU_PREFIX(roleID));
                    if (tRoleEquList==null){
                        tRoleEquList=new ArrayList<TRoleEqu>();
                    }
                    tRoleEquList.add(roleEqu);
                    modelCacheService.addListByPrefixID(ModelCacheService.EQU_PREFIX(roleID),tRoleEquList);

                    /***
                     * notify client
                     */
                    notifyEquResponse.Builder builder=notifyEquResponse.newBuilder();
                    equVO.Builder equ=equVO.newBuilder();
                    equ.setEquID(roleEqu.getEquid());
                    equ.setEquTypeID(roleEqu.getEqutypeid());
                    equ.setEquLevel(roleEqu.getEqulevel());
                    equ.setEquTimeOut(roleEqu.getEqutimeout());
                    equ.setEquLocation(roleEqu.getEqulocation());
                    equ.setEquPinZhi(roleEqu.getEqupinzhi());
                    equ.setEquPinJie(roleEqu.getEqupinjie());
                    equ.setEquPinJieExp(roleEqu.getEqupinjieexp());


                    Double effectnum=roleEqu.getEffectnum1();
                    Double effectnumgrowup=roleEqu.getEffectnumgrowup1();

                    if (effectnum!=null) equ.setEffectNum1(effectnum);
                    if (effectnumgrowup!=null)equ.setEffectNumGrowUp1(effectnumgrowup);

                    effectnum=roleEqu.getEffectnum2();
                    effectnumgrowup=roleEqu.getEffectnumgrowup2();

                    if (effectnum!=null)equ.setEffectNum2(effectnum);
                    if (effectnumgrowup!=null)equ.setEffectNumGrowUp2(effectnumgrowup);

                    effectnum=roleEqu.getEffectnum3();
                    effectnumgrowup=roleEqu.getEffectnumgrowup3();
                    if (effectnum!=null) equ.setEffectNum3(effectnum);
                    if (effectnumgrowup!=null)equ.setEffectNumGrowUp3(effectnumgrowup);

                    equ.setItemType(roleEqu.getItemtype());
                    builder.setType(roleEqu.getEqutype());
                    builder.setEqu(equ.build());
                    //推送更新消息
                    gameCharacter.DirectSend(CardBox.wrappedBufferShort(notifyEquResponse.msgID.ID_VALUE,builder.build()));
                }
                return;
            }

            //秘籍
            if (items[0x3]==0x2){
                BookModel bookModel=ScriptFactory.bookModelFastMap.get(items[0x1]);
                if (bookModel!=null){
                    if (useItemLog){
                        TItemLog itemLog=new  TItemLog();
                        itemLog.setRoleid(roleID);
                        itemLog.setCreattime(new Date());
                        itemLog.setOpttype(optType);

                        itemLog.setItemtypeid(bookModel.getId());   //物品类型ID
                        itemLog.setItemname(bookModel.getName());
                        itemLog.setInfo(bookModel.getIntro());
                        //log item
                        this.itemLogMapper.insert(itemLog);    //数据库自增ID
                    }
                    TRoleBook roleBook=new TRoleBook();
                    roleBook.setOwnerid(roleID);
                    roleBook.setBooktypeid(bookModel.getId());   //物品编号
                    roleBook.setBooktype(bookModel.getType().byteValue());   //部位、类型
                    roleBook.setBookpinzhi(bookModel.getQuality().byteValue());   //品质
                    roleBook.setBookpinjie(bookModel.getSubQuality().byteValue());  //品阶
                    roleBook.setBookpinjieexp(0);
                    roleBook.setBooklevel(bookModel.getUpgradeLevelMax());//强化等级
                    roleBook.setBookprice(bookModel.getPrice());
                    roleBook.setBooktimeout((long) 0);    //time out
                    roleBook.setBooklocation((byte) -1);
                    roleBook.setBookshowbag(bookModel.getShowInBag());  //show bag
                    roleBook.setBooksuccessusetimes(0);
                    roleBook.setItemtype(bookModel.getItemType());  //秘籍类型 2
                    roleBook.setBooksuccessusetimes(0);

                    tRoleBookMapper.insert(roleBook);
                    List<TRoleBook> tRoleItems= (List<TRoleBook>)
                            modelCacheService.findListByPrefixID(ModelCacheService.BOOK_PREFIX(roleID));
                    if (tRoleItems==null){
                        tRoleItems=new ArrayList<TRoleBook>();
                    }
                    tRoleItems.add(roleBook);
                    modelCacheService.addListByPrefixID(ModelCacheService.BOOK_PREFIX(roleID),tRoleItems);
                    /***
                     * notify client
                     */
                    notifyBookResponse.Builder  bookVo=notifyBookResponse.newBuilder();
                    bookVO.Builder book=bookVO.newBuilder();
                    book.setBookID(roleBook.getBookid());
                    book.setBookTypeID(roleBook.getBooktypeid());
                    book.setBookSuccessUseTimes(roleBook.getBooksuccessusetimes());
                    book.setBookTimeOut(roleBook.getBooktimeout());
                    book.setBookLocation(roleBook.getBooklocation());
                    book.setBookPinZhi(roleBook.getBookpinzhi());
                    book.setBookPinJie(roleBook.getBookpinjie());
                    book.setBookPinJieExp(roleBook.getBookpinjieexp());
                    book.setItemType(roleBook.getItemtype());
                    bookVo.setType(roleBook.getBooktype());
                    bookVo.setBook(book.build());
                    gameCharacter.DirectSend(CardBox.wrappedBufferShort(notifyBookResponse.msgID.ID_VALUE,bookVo.build()));
                }
                return;
            }
            //道具
            if (items[0x3]== 0x3){ //道具
                PropsModel propsModel=ScriptFactory.itemModelFastMap.get(items[0x1]);
                if (propsModel!=null){
                    if (useItemLog){
                        TItemLog itemLog=new  TItemLog();
                        itemLog.setRoleid(roleID);
                        itemLog.setCreattime(new Date());
                        itemLog.setOpttype(optType);
                        itemLog.setItemtypeid(propsModel.getId());
                        itemLog.setItemname(propsModel.getName());
                        itemLog.setInfo(propsModel.getIntro());
                        //log item
                        this.itemLogMapper.insert(itemLog);
                    }
                    //记录到玩家的物品数据表中
                    TRoleItemProps  itemProps=new TRoleItemProps();
                    itemProps.setOwnerid(roleID);
                    itemProps.setPropstypeid(propsModel.getId());
                    itemProps.setItemtype(propsModel.getItemType());//道具类型 3
                    itemProps.setPropspinzhi(propsModel.getQuality().byteValue());
                    itemProps.setPropstimeout((long)0);
                    itemProps.setPropsnum(num); //同一类型道具，叠加
                    itemProps.setDayuselimit(propsModel.getDayUseLimit());
                    itemProps.setType(propsModel.getType().byteValue());  //部位/类型


                    tRoleItemPropsMapper.insert(itemProps);
                    List<TRoleItemProps> itemPropses=
                            (List<TRoleItemProps>) modelCacheService.findListByPrefixID(ModelCacheService.PROPS_PREFIX(roleID));
                    //if creat role
                    if (itemPropses==null){
                        itemPropses=new ArrayList<TRoleItemProps>();
                    }
                    itemPropses.add(itemProps);
                    modelCacheService.addListByPrefixID(ModelCacheService.PROPS_PREFIX(roleID),itemPropses);
                    /***
                     * notify client
                     */
                    notifyItemResponse.Builder builder=notifyItemResponse.newBuilder();
                    itemVO.Builder item=itemVO.newBuilder();
                    item.setItemID(itemProps.getPropsid());//道具编号 来自数据库自增长
                    item.setItemTypeID(itemProps.getPropstypeid());
                    item.setItemNum(itemProps.getPropsnum());
                    item.setItemTimeOut(itemProps.getPropstimeout());
                    builder.setType(itemProps.getType());
                    builder.setItem(item.build());
                    gameCharacter.DirectSend(CardBox.wrappedBufferShort(notifyItemResponse.msgID.ID_VALUE,builder.build()));
                }
            }
        } catch (dataException e){
            throw new dataException("插入数据异常", e);
        }
    }



    /**
     * 登记玩家物品信息
     * 首先更新数据库，然后更新数据cache
     * @param roleID
     * @param itemID
     * @param itemType
     * @param optType
     */
    @Transactional
    public Serializable recordGoods(int roleID,int itemID,int itemType,String optType){
        try{
            boolean useItemLog= Config.DEFAULT_VALUE.GAME_VALUE.useItemLog;

            //装备
            if (itemType== 0x1){
                EquipmentModel equipmentModel= ScriptFactory.equipmentModelFastMap.get(itemID);
                if (useItemLog){
                    TItemLog itemLog=new  TItemLog();
                    itemLog.setRoleid(roleID);
                    itemLog.setCreattime(new Date());
                    itemLog.setOpttype(optType);
                    itemLog.setItemtypeid(equipmentModel.getId());
                    itemLog.setItemname(equipmentModel.getName());
                    itemLog.setInfo(equipmentModel.getIntro());
                    //log item
                    this.itemLogMapper.insert(itemLog); //物品日志记录
                }

                //记录到玩家的物品数据表中
                //记录到玩家的物品数据表中
                TRoleEqu roleEqu=new TRoleEqu();
                roleEqu.setOwnerid(roleID);  //装备所属对象
                roleEqu.setEqutypeid(equipmentModel.getId());   //物品编号
                roleEqu.setEqutype(equipmentModel.getType().byteValue());   //部位、类型
                roleEqu.setEqupinzhi(equipmentModel.getQuality().byteValue());   //品质
                roleEqu.setEqupinjie(equipmentModel.getSubQuality().byteValue());  //品阶
                roleEqu.setEqulevel(equipmentModel.getUpgradeLevelMax());//强化等级
                roleEqu.setEquprice(equipmentModel.getPrice());
                roleEqu.setEqutimeout(null);    //time out
                roleEqu.setEqushowbag(equipmentModel.getShowInBag());  //show bag
                roleEqu.setEqulocation((byte) 0);
                roleEqu.setEqupinjieexp(0);
                roleEqu.setItemtype(equipmentModel.getItemType());  //装备类型 1

                tRoleEquMapper.insert(roleEqu);  //
                List<TRoleEqu> tRoleEquList=
                        (List<TRoleEqu>) modelCacheService.findListByPrefixID(ModelCacheService.EQU_PREFIX(roleID));
                tRoleEquList.add(roleEqu);
                modelCacheService.addListByPrefixID(ModelCacheService.EQU_PREFIX(roleID),tRoleEquList);
                return roleEqu;
            }

            //秘籍
            if (itemType== 0x2){
                BookModel bookModel=ScriptFactory.bookModelFastMap.get(itemID);
                if (useItemLog){
                    TItemLog itemLog=new  TItemLog();
                    itemLog.setRoleid(roleID);
                    itemLog.setCreattime(new Date());
                    itemLog.setOpttype(optType);

                    itemLog.setItemtypeid(bookModel.getId());   //物品类型ID
                    itemLog.setItemname(bookModel.getName());
                    itemLog.setInfo(bookModel.getIntro());
                    //log item
                    this.itemLogMapper.insert(itemLog);    //数据库自增ID
                }

                TRoleBook roleBook=new TRoleBook();
                roleBook.setOwnerid(roleID);
                roleBook.setBooktypeid(bookModel.getId());   //物品编号
                roleBook.setBooktype(bookModel.getType().byteValue());   //部位、类型
                roleBook.setBookpinzhi(bookModel.getQuality().byteValue());   //品质
                roleBook.setBookpinjie(bookModel.getSubQuality().byteValue());  //品阶
                roleBook.setBookpinjieexp(0);
                roleBook.setBooklevel(bookModel.getUpgradeLevelMax());//强化等级
                roleBook.setBookprice(bookModel.getPrice());
                roleBook.setBooktimeout(null);    //time out
                roleBook.setBooklocation((byte) 0);
                roleBook.setBookshowbag(bookModel.getShowInBag());  //show bag
                roleBook.setBooksuccessusetimes(0);
                roleBook.setItemtype(bookModel.getItemType());  //秘籍类型 2
                /**
                 * set attr
                 */
                tRoleBookMapper.insert(roleBook);
                List<TRoleBook> tRoleItems= (List<TRoleBook>)
                        modelCacheService.findListByPrefixID(ModelCacheService.BOOK_PREFIX(roleID));
                tRoleItems.add(roleBook);
                modelCacheService.addListByPrefixID(ModelCacheService.BOOK_PREFIX(roleID),tRoleItems);
                return roleBook;

            }

            //道具
            if (itemType== 0x3){
                PropsModel propsModel=ScriptFactory.itemModelFastMap.get(itemID);
                if (useItemLog){
                    TItemLog itemLog=new  TItemLog();
                    itemLog.setRoleid(roleID);
                    itemLog.setCreattime(new Date());
                    itemLog.setOpttype(optType);
                    itemLog.setItemtypeid(propsModel.getId());
                    itemLog.setItemname(propsModel.getName());
                    itemLog.setInfo(propsModel.getIntro());
                    //log item
                    this.itemLogMapper.insert(itemLog);
                }

                //记录到玩家的物品数据表中
                TRoleItemProps itemProps=new TRoleItemProps();
                itemProps.setOwnerid(roleID);
                itemProps.setPropstypeid(propsModel.getId());
                itemProps.setItemtype(propsModel.getItemType());//道具类型 3
                itemProps.setPropspinzhi(propsModel.getQuality().byteValue());
                itemProps.setPropstimeout(null);
                /**
                 *   set attr
                 */
                tRoleItemPropsMapper.insert(itemProps);
                List<TRoleItemProps> itemPropses=
                        (List<TRoleItemProps>) modelCacheService.findListByPrefixID(ModelCacheService.PROPS_PREFIX(roleID));
                itemPropses.add(itemProps);
                modelCacheService.addListByPrefixID(ModelCacheService.PROPS_PREFIX(roleID),itemPropses);
                return  itemProps;
            }
        } catch (dataException e){
            throw new dataException("插入数据异常", e);
        }
        return null;
    }



    /**
     * 修改数据库 更新缓存
     * 脱下（装备，秘籍，技能）
     * @param o   角色ID
     * 功法书？！
     *
     */
    @Transactional
    public boolean takeOff(Object o){
        boolean status =false;
        try {
            if (o instanceof TRoleEqu){
                tRoleEquMapper.updateByPrimaryKeySelective((TRoleEqu)o);
                status=true;
                return status;
            }
            if (o instanceof TRoleBook){
                tRoleBookMapper.updateByPrimaryKeySelective((TRoleBook) o);
                return status;
            }
        }catch (dataException e){
            throw new dataException("Transactional error ,please check logic");
        }
        return status;
    }

    /**
     * 修改数据库 更新缓存
     * 穿上（装备，秘籍，技能）
     * @param o
     */
    @Transactional
    public boolean putOn(Object o){
        boolean status =false;
        try {

            if (o instanceof TRoleEqu){
                tRoleEquMapper.updateByPrimaryKeySelective((TRoleEqu)o);
                status=true;
                return status;
            }
            if (o instanceof TRoleBook){
                tRoleBookMapper.updateByPrimaryKeySelective((TRoleBook) o);
                return status;
            }
            if (o instanceof TSprite){
                this.tSpriteMapper.updateByPrimaryKeySelective((TSprite) o);
                return status;
            }

        }catch (dataException e){
            throw new dataException("Transactional error ,please check logic");
        }
        return status;
    }

    /**
     * 修改数据库 更新缓存
     * 购买物品 （装备，秘籍，技能）
     * @param roleID  角色ID
     *                购买的物品编号，物品类型 （itemType）
     *                灵石数量更改
     */
    public void buy(int roleID){


    }

    /**
     * 修改数据库 更新缓存
     * 出售交易物品 （装备，秘籍，技能）
     * @param roleID    角色ID
     *                  交易的物品编号，物品类型 （itemType）
     *                  灵石数量更改
     *                  装备 秘籍  道具
     */
    public void  tradeToSystem(int roleID){

    }


    /**
     * 道具消耗品的使用
     * @param roleID   角色ID
     */
    public void useProps(int roleID){

    }

}
